package fluent_pro_as;

import org.testng.annotations.Test;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;

import org.testng.*;
import org.testng.annotations.*;

import static org.hamcrest.CoreMatchers.*;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.ArrayList;


public class CreateActions extends fluent_pro_as.pages.TestBase {
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();
	 
 
public void login(String name, String password){
	
	 WebElement USERNAME = driver.findElement(By.id("username"));
	 WebElement PASSWORD = driver.findElement(By.id("password"));
	 USERNAME.clear();
	 USERNAME.sendKeys(name);
	 PASSWORD.clear();
	 PASSWORD.sendKeys(password);
	 driver.findElement(By.cssSelector("div.checkbox + input.btn")).click();	 
 }
 
public void logout(){
	   
	   WebDriverWait wait = new WebDriverWait(driver, 10); 
	   Actions builder = new Actions(driver);
	   builder.moveToElement(driver.findElement(By.cssSelector("div#header .dropdown"))).build().perform();
	   wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[href$='Logout']")));
	   driver.findElement(By.cssSelector("a[href$='Logout']")).click();
  }
 
public void createAction(String subject, String assignee){
		
	  driver.findElement(By.cssSelector("a[href$='webActionRegistry/']")).click();
	  driver.findElement(By.cssSelector("#actionregistry-create-action > .btn")).click();
	  driver.findElement(By.id("form_subject")).clear();
	  driver.findElement(By.id("form_subject")).sendKeys(subject);
	  driver.findElement(By.id("token-input-form_assignees")).sendKeys(assignee);
	    
	   //wait for dropdown item  WebElement element = new WebDriverWait(driver, 5)
	  WebDriverWait wait = new WebDriverWait(driver, 5);
	  wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".token-input-dropdown-item2.token-input-selected-dropdown-item")));
	   driver.findElement(By.cssSelector(".token-input-dropdown-item2.token-input-selected-dropdown-item")).click();
	   driver.findElement(By.id("form_notes")).clear();
	   driver.findElement(By.id("form_notes")).sendKeys("Example of Action"+Keys.RETURN);
	   driver.findElement(By.cssSelector("input.btn")).click();	 
 }
 
public void findActiveActions(){
	   
	    WebDriverWait wait = new WebDriverWait(driver, 10);
	    Actions builder = new Actions(driver);   
	        
	    driver.findElement(By.cssSelector("#header a[href$='webActionRegistry/']")).click();
	    wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("div#actionregistry-view-selector .dropdown")));
	    builder.moveToElement(driver.findElement(By.cssSelector("div#actionregistry-view-selector .dropdown"))).build().perform();
	    wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[href$='actUpdateFilter&view=active']")));
	    driver.findElement(By.cssSelector("a[href$='actUpdateFilter&view=active']")).click();
	    driver.findElement(By.cssSelector("form#actionregistry-view-active input.btn")).click();
	    wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".dataTables_info")));
}
 
public void completeAction(){
	    
	    driver.findElement(By.cssSelector("a#act-signoff")).click();
	    driver.switchTo().frame(driver.findElement(By.tagName("iframe"))); 
	    WebElement STATUSES = driver.findElement(By.tagName("select"));
	    Select select = new Select(STATUSES);
	    select.selectByVisibleText("Completed");
	    driver.findElement(By.cssSelector("textarea#comment")).clear();
	    driver.findElement(By.cssSelector("textarea#comment")).sendKeys("Complete the Action");
	    driver.findElement(By.cssSelector("div[class='form-container actionpage'] input.btn")).click();
	    driver.switchTo().defaultContent();
 }
 
 @Test
  public void addAction() throws Exception {
   
	driver.get(baseUrl + "/TIBCONimbus9.2.1.82/CtrlWebIsapi.dll");
	
	login("user.1", "123456");

	createAction("TIBCO", "user 2");
   
    logout(); 
    
    login("user.2", "123456");
        
    findActiveActions();
        
    /* create array of names of all active Actions before completing
     (I think it's more reliable to create array of Action ID - Numbers as names can be duplicated)
     but for illustration I create arrays of names. */
    
    //find total count of rows in the table
    int k1 = driver.findElement(By.cssSelector("#actionregistry")).findElements(By.tagName("tr")).size();
    //create a new array
    ArrayList<String> ACTION_NAMES_INITIAL = new ArrayList<String>();
    for (int i=1; i<k1; i++){
	   WebElement NAME_CELL = driver.findElement(By.cssSelector("#actionregistry")).findElements(By.tagName("tr")).get(i).findElements(By.tagName("td")).get(3);
	   String NAME = NAME_CELL.getText();
	   ACTION_NAMES_INITIAL.add(NAME);
     }
    //find total count of names in the created array
    int S1 = ACTION_NAMES_INITIAL.size(); 
    
    //go to the created Action - it always appears in the end of the table
    WebElement ACTION_CELL = driver.findElement(By.cssSelector("#actionregistry")).findElements(By.tagName("tr")).get(k1-1).findElements(By.tagName("td")).get(1);
    ACTION_CELL.findElement(By.cssSelector("a.i-want-to")).click();
        
    completeAction();
    
    findActiveActions();
      
    //find count of all active Actions, that remain after Action completion 
    int k2 = driver.findElement(By.cssSelector("#actionregistry")).findElements(By.tagName("tr")).size();
    //create a new array with these elements
    ArrayList<String> ACTION_NAMES_RESULT = new ArrayList<String>();
    for (int i=1; i<k2; i++){
 	   WebElement NAME_CELL = driver.findElement(By.cssSelector("#actionregistry")).findElements(By.tagName("tr")).get(i).findElements(By.tagName("td")).get(3);
 	   String NAME = NAME_CELL.getText();
 	   ACTION_NAMES_RESULT.add(NAME);
     }
   //find total count of names in the created array
    int S2 = ACTION_NAMES_RESULT.size();
   
  /*Condition test completion: compare number of Action before & after completing and check that completed Action doesn't exist in the table
    as I wrote before -check for Action numbers is more reliable as Numbers cannot be duplicated*/
    
    if ((ACTION_NAMES_RESULT.size()+1) == ACTION_NAMES_INITIAL.size() && ACTION_NAMES_RESULT.indexOf(ACTION_NAMES_INITIAL.get(S1-1))==-1){
 	   System.out.println("PASS");
    }
    else{
 	   System.out.println("FAIL");
    }
       
    
  //Print the tested Action - it's the name of the last action in the table, that should be completed
   System.out.println("You have created "+ACTION_NAMES_INITIAL.get(S1-1)+ " Action");
   //Print initial number of all Actions and their names
   System.out.println(S1+" Active Action(s) were assigned to user in the beginning. "+"They were: "+ACTION_NAMES_INITIAL);
   //Print final number of all Actions and their names
   System.out.println(S2+" Active Action(s) remain. " + "They are: "+ ACTION_NAMES_RESULT);

   

   


  }

  private boolean isElementPresent(By by) {
    try {
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }

  private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      String alertText = alert.getText();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alertText;
    } finally {
      acceptNextAlert = true;
    }
  }
}
